<?php
/*
 * [JINYUN!] (C)2001-2099 Jinyunweb.com
 * This is NOT a freeware, use is subject to license terms
 * 商品分类
*/
defined('BY_JYA') or exit('error');
$_RQ['op']=$_RQ['op']?$_RQ['op']:'main';
$merchid=$worker['merchid'];
if($_RQ['op']=='main'){
	if(!$_RQ['id']){
		exi('请从问诊订单进入!','error');
	}
	$item=pdo_get('jy_yiliao_lesson_log',array('uniacid'=>$_SESSION['uniacid'],'id'=>$_RQ['id']));
	$item['workertitle']=pdo_getcolumn('jy_yiliao_worker',array('uniacid'=>$_SESSION['uniacid'],'id'=>$item['worker_id']),'name');
	if(!$item['username']){
		$user=pdo_get('jy_yiliao_user',array('uniacid'=>$_SESSION['uniacid'],'mid'=>$item['mid']),array('name','birth','sex','mobile'));
		$item['username']=$user['name'];
		$item['name']=$user['name'];
		$item['mobile']=$user['mobile'];
		$item['sex']=$user['sex'];
		$item['birth']=json_decode($user['birth'],true);
		$item['year']=$item['birth']['year'];
		if($item['bodyid']){
			$body=pdo_get('jy_yiliao_body',array('uniacid'=>$_SESSION['uniacid'],'id'=>$item['bodyid']),array('name','sex','agetime'));
			$item['name']=$body['name'];
			$item['sex']=$body['sex'];
			$item['year']=date('Y',$body['agetime']);
		}
	}
	$item['name']=$item['name']?:'无';
	$item['sex']=$item['sex']==1?'男':'女';
	$item['age']=$item['year']>0?date('Y')-$item['year']:'无';
	$myshop=$store=pdo_get('jy_merch_user',array('uniacid'=>$_SESSION['uniacid'],'id'=>$merchid));	
    $return['myshop'] = $myshop;
    //商户没有商品分类需要新增一条默认分类数据
    $onegroups=pdo_count('jy_weishop_goods_group',array('uniacid'=>$_SESSION['uniacid'],'merchid'=>$merchid));
    if($onegroups==0){
        pdo_insert('jy_weishop_goods_group',array('uniacid'=>$_SESSION['uniacid'],'title'=>'默认分类','merchid'=>$merchid));
    }
    if($_SESSION['member']['username'] && $worker){
        $return['jobnum'] = $_SESSION['member']['username'];
    }else{
        $return['jobnum'] = $myshop['wnum'];
    }
	$ptgroup = pdo_getall('jy_weishop_goods_group',array('merchid'=>0,'uniacid'=>$_SESSION['uniacid']));
	$shgroup = pdo_getall('jy_weishop_goods_group',array('merchid'=>$merchid,'uniacid'=>$_SESSION['uniacid']));
	if($ptgroup && !$shgroup){
	    $params=array('merchid'=>0,'isshow'=>1,'parentid'=>0,'uniacid'=>$_SESSION['uniacid'],'onepluginname OR'=>'onepluginname=\'jy_merch\' or onepluginname=\'\'');
	}
	if(!$ptgroup && $shgroup){
	    $params=array('merchid'=>$merchid,'isshow'=>1,'parentid'=>0,'uniacid'=>$_SESSION['uniacid'],'onepluginname OR'=>'onepluginname=\'jy_merch\' or onepluginname=\'\'');
	}
	if($ptgroup && $shgroup){
	    $params=array('isshow'=>1,'parentid'=>0,'uniacid'=>$_SESSION['uniacid'],'merchid OR'=>'merchid='.$merchid.' or merchid=\'0\'','onepluginname OR'=>'onepluginname=\'jy_merch\' or onepluginname=\'\'');
	}
	$groups=pdo_getall('jy_weishop_goods_group',$params,array('id','title','parentid'));
	if(empty($groups)){
		$groups=pdo_getall('jy_weishop_goods_group',array('onepluginname'=>'','merchid'=>0,'uniacid'=>$_SESSION['uniacid'],'isshow'=>1,'parentid'=>0),array('id','title','parentid'));
	}
	$return['item']=$item;
	$return['merchid']=$merchid;
	$return['params']['pcate'] =$params['pcate']?$params['pcate']:0;
	$return['list']=array();
	$return['groups']=$groups;
	$return['in_pay']=$store['in_pay'];
	$return['allnum']=0;
	$return['allprice']=0;
	$return['orderprice']=0;
	$return['order_type']=$this->session('order_type');
	$return['post']=array('mobile'=>$item['mobile'],'mid'=>$item['mid'],'merchid'=>$merchid,'sendtype'=>'2','paytype'=>2,'is_pay'=>1);
	exi($return);
}
if($_RQ['op']=='getlist'){
	$carts=$this->session('carts'); 
	$allnum =0;
	if($carts){
		foreach($carts as $k=>&$v){
			$allnum += $v['num'];
		}
	}else{
		$carts = array();
	}
	$params=array('merchid'=>$merchid,'status'=>1);
	$params['uniacid']=$_SESSION['uniacid'];
	if($_RQ['pcate']){
		$pcate = intval($_RQ['pcate']);
		$params['pcate2']=$pcate;
	}
	if(!empty($_RQ['title'])){
		$params['title like']='%'.trim($_RQ['title']).'%';
		$return['params']['title']=$_RQ['title'];
	}
	$pindex = max(1, intval($_RQ['page']));
	$psize = 30;
	$total='';
	$fields=array('id','title','pcate','status','storeid','image','price','isoption','vipprice');
	$list=pdo_getslice('jy_weishop_goods',$params,array($pindex,$psize),$total,$fields,'id','id desc');
	
	if(!$list && intval($_RQ['pcate'])){
		unset($params['pcate2']);
		$params['pcate']=intval($_RQ['pcate']);
		$list=pdo_getslice('jy_weishop_goods',$params,array($pindex,$psize),$total,$fields,'id','id desc');
	}
	if($list){
		$goodsprice=0;
		foreach($list as $k=>&$g){
			if(!$g['title']){
				unset($list[$k]);
				continue;
			}
			$g['cartnum']= $carts[$g['id']]['num'] >0 ? $carts[$g['id']]['num'] : 0;
			$goodsprice += $g['cartnum']*$g['price'];
			//规格
			$specs_list=pdo_getall('jy_weishop_goods_spec',array('goodsid'=>$g['id'],'uniacid'=>$_SESSION['uniacid']),array('id','title'),'','paixu asc');
			//已选规格
			$selectspecs = array();
			$selespename = '';
			if($specs_list){
					foreach($specs_list as $k=>&$sp){
						$sp['items']=pdo_getall('jy_weishop_goods_spec_item',array('specid'=>$sp['id'],'uniacid'=>$_SESSION['uniacid']),array('id','title'),'','paixu asc');
						$selectspecs[$k]=$sp['items'][0]['id'];
						$selespename .=$sp['items'][0]['title'].'，';
					}
			}
			//默认已选参数：
			$spsids = '';
			foreach($selectspecs as $k=>&$s){
					if($k==0){
						$spsids .= $s;
					}else{
						$spsids .= '_'.$s;
					}
			}
			$g['options'] = pdo_get('jy_weishop_goods_option',array('goodsid'=>$g['id'],'specs'=>$spsids));
			//默认商品规格价格：
			if($g['options']){
				$g['isoption']=1;
				$g['price']=$g['options']['price'];
			}
			$g['selespename'] = $selespename;
			$option_list=pdo_getall('jy_weishop_goods_option',array('uniacid'=>$_SESSION['uniacid'],'goodsid'=>$g['id']),array('id','specs','thumb','stock','price','productprice','costprice','goodssn','productsn','weight'),'','paixu asc');
			if($option_list){
					foreach($option_list as &$i){
						$i['specs']=explode('_',$i['specs']);
						foreach($i['specs'] as $j){
							$op=pdo_get('jy_weishop_goods_spec_item',array('id'=>intval($j)),array('specid','title'));
							$spec_title=pdo_getcolumn('jy_weishop_goods_spec',array('id'=>$op['specid']),'title');
							$i[$spec_title]=$op['title'];
						}
						$i['num']=$i['stock'];
						$i['old_price']=$i['productprice'];
						$i['cost_price']=$i['costprice'];
						$i['bm']=$i['goodssn'];
						$i['tm']=$i['productsn'];
						$i['image']=$i['thumb'];
					}
					$specs_list['option']=$option_list;
			}
			$g['specs_list'] = $specs_list;
			if(!$g['pcate2'] && $g['pcate']){
				pdo_update('jy_weishop_goods',array('pcate2'=>$g['pcate'],'ccate2'=>$g['ccate'],'scate2'=>$g['scate']),array('id'=>$g['id'], 'uniacid' => $_SESSION['uniacid']));
			}
		}

	}
	$return['list']=$list;
	$totalpage=ceil($total/$psize);
	$totalpage=intval($totalpage);
	$return['totalpage'] =$totalpage;
	$return['params']['page'] =$pindex;
	//
	$allprice = $goodsprice - $youhui - $molin;
	$return['allnum']=$allnum;
	$return['allprice']=$allprice;
	$return['orderprice']=$allprice;
	$return['carts']=$carts;
	exi($return);
}
if($_RQ['op']=='diancai'){
	$post=get_postdata();
	$goodid=intval($post['goodid']);
	$num=intval($post['num']);
	$optionsid=intval($post['optionsid']);
	$carts=$this->session('carts');
	if(!$carts){
		$carts=array();
	}
	if($num < 1){
		unset($carts[$goodid]);
	}else{
		$carts[$goodid]['num']=$num;
		$goodinfo=pdo_get('jy_weishop_goods',array('uniacid'=>$_SESSION['uniacid'],'id'=>$goodid));
		$carts[$goodid]['goodstitle'] = $goodinfo['title'];
		$carts[$goodid]['goodsprice'] = $goodinfo['price'];
		$packageinfo=json_decode($goodinfo['package'],true);
		$package=$carts[$goodid]['package'];
		if(!empty($packageinfo)){
			foreach($packageinfo as $k=>&$v){
				if($k == $packageid){
					$package[$k]['title']=$v['title'];
					$package[$k]['price']=$v['price']?$v['price']:$goodinfo['price'];
					if($_RQ['plus']){
						$package[$k]['num'] +=1;
					}else{
						$package[$k]['num'] -=1;
						if($package[$k]['num'] == 0){
							unset($package[$k]);
						}
					}
				}
			}
			$carts[$goodid]['package'] = $package;
		}
	}
	$carts=$this->session('carts',$carts);

	$return['carts'] = $this->session('carts');
	exi($return);
}
if($_RQ['op']=='get_optionsid'){
	$post=get_postdata();
	$id=$post['goodsid'];
	if(!$id){
		exi('请先选择商品！','error');
	}
	$return['options'] = pdo_get('jy_weishop_goods_option',array('goodsid'=>$id,'specs'=>$post['specid']));
	exi($return);
}
if($_RQ['op']=='unsetcarts'){
	$carts=$this->session('carts',array());
	$return['carts'] = $this->session('carts');
	exi($return);
}
if($_RQ['op']=='addorder'){
	$post=get_postdata();
	//商品合计金额   level_de_price(会员折扣金额)  endprice(实际金额) 
	$money = $post['money'];  
	$carts=$post['carts'];

	$store=pdo_get('jy_weishop_store',array('id'=>$store_id));
	$youhui = 0;
	//收银台优惠设置生效
	if(!$carts && !$post['oldorderid']){
		exi('没有选择商品！','error');
	}
	if(!$post['paytype'] && !$post['auth_code']){
	    exi('请扫描微信或支付宝付款码','error');
	}
	$total=0;
	//处理订单
	if($carts){
		//从购物车购买
		foreach($carts as $k=>&$cart){
			$goods=pdo_get('jy_weishop_goods',array('id'=>$k),array('type','title','image','price','total','totalcnf','weight','active_plugin','active_id','storeids','merchid'));
			if(!$goods){
				exi('指定商品不存在！','error');
			}
			$goods['goodsid']=$k;
			$goods['total']=$cart['num'];
			$goods['price']=$cart['price'];
			model('jy_weishop/goods')->check_buy($goods['id'],$cart['num']);
			if($cart['options']){
				foreach($cart['options'] as $ov){
					$option_goods=pdo_get('jy_weishop_goods_option',array('id'=>$ov['id'],'uniacid'=>$_SESSION['uniacid'],'goodsid'=>$goods['goodsid']),array('price','stock','specs'));
					if(!$option_goods){
						exi('指定商品规格不存在！','error');
					}
					$specs = explode("_", $option_goods['specs']);
					$specsall = pdo_getall('jy_weishop_goods_spec_item',array('id'=>$specs,'uniacid'=>$_SESSION['uniacid']),array('id','title'),'','paixu asc');
					if($specsall){
						$optiontitle='';
						foreach($specsall as $k2=>$sp){
							if($k2==0){
								$optiontitle .=$sp['title'];
							}else{
								$optiontitle .='，'.$sp['title'];
							}
						}
					}
					$goods['optiondata']= $optiontitle;
					$goods['price']=$option_goods['price'];
					$goods['total']=$ov['num'];
					$goods['optionid']=$ov['id'];
				}
			}
			//来自商户的分销(商户员工团长分销)
			$cart['merchid']=$cart['merchid']?$cart['merchid']:$goods['merchid'];
			$cart=array_merge($goods,$cart);
		}
		$order=array(
			'type'=>'cart',
			'list'=>$carts,
		);
	}

	//处理订单
	if(empty($order['list']) && !$post['oldorderid']){
		exi('请先选择商品再下单！','error');
	}
	foreach($order['list'] as &$goods){
		if($goods['type']==6){
			$api_data=pdo_getcolumn('jy_weishop_goods',array('id'=>$goods['goodsid'],'uniacid'=>$_SESSION['uniacid']),'api_data');
			$goods['api_data']=json_decode($api_data,true);
		}
		if($goods['active_plugin']){
			//商品在做活动，检查下库存是否不足
			model('jy_weishop/activity')->check_stock($goods['id'],$goods['active_plugin'],$goods['active_id'],$goods['total']);
			$active=model('jy_weishop/activity')->get_active($goods['id'],$goods['active_id'],$goods['active_plugin']);
			if($active['price']){
				$goods['price']=$active['price'];
				$goods['active']=$active;
			}
		}
	}

	if($post['oldorderid']){
		$order['oldorderid']=$post['oldorderid'];
		$oldorders=pdo_getall('jy_weishop_order_goods',array('uniacid'=>$_SESSION['uniacid'],'orderid'=>$post['oldorderid']));
		foreach($oldorders as &$oov){
			$oov['isold']=1;
			$order['list'][]=$oov;
		}
	}
	//统计订单商品总数和总价
	$total=0;
	$total_price=0.00;
	$total_weight=0;
	
	foreach($order['list'] as $vc){
		$total+=$vc['total'];
		$total_price+=$vc['total']*$vc['price'];
		$total_weight+=$vc['weight']*$vc['total'];
	}
	
	$order['total']=$total;
	$order['total_price']=$total_price;
	$order['total_weight']=round($total_weight/1000,2);
	//计算运费
	if(!$order['sendtype'] || $order['sendtype']==1){
		$dispatch=pdo_get('jy_weishop_dispatch',array('uniacid'=>$_SESSION['uniacid'],'isdefault'=>1));
		if(!$dispatch){
			$dispatch=pdo_get('jy_weishop_dispatch',array('uniacid'=>$_SESSION['uniacid']));
		}
		if(!$dispatch){
			$order['dispatchprice']=0.00;
		}else{
			$order['dispatchprice']=$dispatch['showprice'];
			if($order['total_weight']>$dispatch['shouweight']){
				$order['dispatchprice']+=$dispatch['xuprice']*ceil(($order['total_weight']-$dispatch['shouweight'])/$dispatch['xuweight']);
			}
		}
	}
	
	//会员折扣价
	$order['level_de_price']=0.00;
	if(!$order['no_member_discount'] && $post['mid']){
		//允许使用会员折扣，整理会员折扣数据
		$member_levelid=pdo_getcolumn('jy_weishop_member',array('mid'=>$post['mid']),'level');
		if($member_levelid){
			$member_level=pdo_get('jy_weishop_member_level',array('id'=>$member_levelid));
			if($member_level){
			    if($member_level['discount']>0){
				   $member_level['discount']=$member_level['discount']?$member_level['discount']:10;
			 	   $order['level_de_price']=$order['total_price'] - $order['total_price']*($member_level['discount']/10);
			    }else{
			         $order['level_de_price']= 0;
			    }
			}
		}
	}
	
	
	//满减优惠价格：
	$sale_enough=$saleset['enough'];
	if($sale_enough){
		foreach($sale_enough as $k=>$ev){
			if($ev['man']>$order['total_price']){
				unset($sale_enough[$k]);
			}
		}
		paixu($sale_enough,'man','desc');
	}
	$order['sale_enough']=$sale_enough;
	$order['enough_de_price']=$sale_enough[0]['jian']?$sale_enough[0]['jian']:0.00;
	//优惠券优化价格：
	$order['coupon_de_price']=$post['coupon_de_price'];
	//整理收货地址信息
	if($post['mid']){
		$member_address=pdo_getall('core_address',array('mid'=>$post['mid']));
		if($member_address){
			foreach($member_address as &$address){
				$address['pcd']=json_decode($address['pcd'],true);
				if($address['isdefault']){
					$item['addressid']=$address['id'];
					$item['address']=$address;
					break;
				}
			}
			if(!$item['addressid']){
				$item['addressid']=$member_address['0']['id'];
				$item['address']=$member_address['0'];
			}
		}
	}
	
	//配送
	$order['deliverytime'] = $post['deliverytime']?$post['deliverytime']:date("m月d日",strtotime("+2 day"));
	//整理最终价
	$order['endprice']=$order['total_price'] + $order['dispatchprice'] - $order['level_de_price']  - $order['coupon_de_price'] - $order['enough_de_price'];
	$order['no_dispatch_price']=$order['total_price'] - $order['level_de_price']  - $order['coupon_de_price'] - $order['enough_de_price'];
	/*
		赠品
		先根据订单金额找赠品，再根据商品找赠品
	*/
	$goods_gifts=pdo_getall('jy_weishop_goods_gift',array('uniacid'=>$_SESSION['uniacid'],'status'=>1,'activity'=>0));
	$current_gift=array();
	if($goods_gifts){
		foreach($goods_gifts as $gift){
			if($gift['orderprice'] && $gift['orderprice']<$order['no_dispatch_price']){
				if(!$current_gift || $current_gift['orderprice']<$gift['orderprice']){
					$current_gift=$gift;
				}
			}
		}
	}
	if(!$current_gift){
		$goods_gifts=pdo_getall('jy_weishop_goods_gift',array('uniacid'=>$_SESSION['uniacid'],'status'=>1,'activity'=>1));
	}
	if($goods_gifts){
		foreach($goods_gifts as $gift){
			if($gift['goodsid']){
				foreach($order['goods'] as $goods){
					if($goods['goodsid']==$gift['goodsid']){
						$current_gift=$gift;
						break;
					}
				}
			}
			if($current_gift){
				break;
			}
		}
	}
	if($current_gift){
		$order['gift_id']=$current_gift['id'];
		$return['gifts']=json_decode($current_gift['gifts'],true);
	}

	//提交订单
	//公共参数
	$new_order=array(
		'mid'=>$post['mid']?$post['mid']:0,
		'goodsprice'=>$order['total_price'],
		'remark'=>trim($post['remark']),
		'goods'=>$order['list'],
		'merchid'=>$order['merchid'],
	);
	$new_order['invoce']=array(
		'type'=>$post['invoicetype'],
		'goodstype'=>$post['invoicegoodstype'],
		'name'=>$post['invoicename'],
		'code'=>$post['invoicecode'],
		'email'=>$post['email'],
	);
	//会员折扣
	if(!$order['no_member_discount'] && $order['level_de_price']){
		$new_order['level_de_price']=$order['level_de_price'];
	}
	//会员总价的计算显示(--实付金额--)
	
	//立省金额的计算
	
	//满减
	$new_order['enough_de_price']=$order['enough_de_price'];
	//优惠券
	$couponid=intval($post['couponid']);
	$new_order['price']=$post['endprice'];
	if($couponid){
		//使用优惠券
		$new_order['couponid']=$couponid;
		$new_order['coupon_de_price']=$post['coupon_de_price'];
		//获取优惠信息
		$getcouponfee=model('jy_weishop/coupon')->getorderfee($couponid,$new_order['price'],$new_order['goodsprice']);
		if($getcouponfee){
			$new_order=array_merge($new_order,$getcouponfee);
		}
	}
	if($order['sendtype']){
		$new_order['sendtype']=$order['sendtype'];
	}else{
		$sendtype=intval($post['sendtype']);
		if(!$sendtype){
			exi('请先选择配送方式！','error');
		}
		$new_order['sendtype']=$sendtype;
	}
	
	if($new_order['sendtype']==1){
		//快递配送
		$new_order['price']+=$order['dispatchprice'];
		$new_order['addressid']=intval($post['addressid']);
		if(!$new_order['addressid']){
			//exi('请先选择收货地址！','error');
		}
		if($post['juli']){
			$merchid=pdo_getcolumn('jy_weishop_goods',array('id'=>$_SESSION['goodsid']),'merchid');
			$l=pdo_get('jy_merch_user',array('uniacid'=>$_SESSION['uniacid'],'id'=>$merchid),array('lat','lng'));
			if($l['lng'] && $l['lat']){
				$d=cfc('tools')->getdistance($post['lat_lng']['lng'],$post['lat_lng']['lat'],$l['lng'],$l['lat']);
				if($d/1000>$post['juli']){
					exi('超出配送距离,无法购买','error','/goods.detail//id='.$_SESSION['goodsid']);
				}
			}
		}		
	}elseif($new_order['sendtype']==2){
		//门店自提
		$new_order['merchid']=$merchid;
	}elseif($new_order['sendtype']==3){
		//虚拟发货
	}
	$new_order['price']=$post['endprice'];

	if($new_order['price']<0){
		exi('订单金额不能为零！','error');
	}
	if($order['gift_id']){
		$new_order['gift_id']=$order['gift_id'];
	}
	$new_order['plugin_name']='jy_merch';
	$new_order['api_data']['merch_dai']=1;
	//剔除已经追加的商品
	if($order['oldorderid']){
		$new_order['oldorderid']=$order['oldorderid'];
		foreach($new_order['goods'] as $k=>$ov){
			if($ov['isold']==1){
				unset($new_order['goods'][$k]);
			}
		}
	}
	$new_order['deduction'] = $post['deduction'];  
	$order_id=model('jy_weishop/order')->create($new_order,$post['mid'],'',true);
	$printerid=pdo_getcolumn('jy_weishop_printer',array('uniacid' =>$_SESSION['uniacid'],'ismerch'=>1,'storeid'=>$worker['storeid'],'pluginname'=>'jy_yiliao'),'id');
	if($printerid){
		model('jy_weishop/printmsg')->storeprint('',$order_id,0,1,$printerid,'',$new_order['goods'],'',1,1);
	}
	exi(array('order_id'=>$order_id));
}
if($_RQ['op']=='post'){
	 $postdata=get_postdata();
   
     if(empty($postdata['endprice'])){
         $postdata['endprice'] = $postdata['money'];
     }
    
	 $TIME=date('ymdhis',time());
	 if($postdata['endprice']<0){
		 exi('请输入正确金额','error');
	 }
	 $order_id=intval($_RQ['order_id']);
	 $order=pdo_get('jy_weishop_order',array('uniacid'=>$_SESSION['uniacid'],'id'=>$order_id));
	if(!$postdata['paytype']){
		 $tid='CS'.$TIME.rand(10000,99999);
		 if(!$postdata['auth_code']){
			 exi('请扫描微信或支付宝付款码','error');
		 }
		if($postdata['memberprice']){
		    $postdata['endprice'] = $postdata['memberprice'] - $order['level_de_price'] - $order['coupon_de_price'];
		}
		$data=array('ordersn'=>$tid,'uniacid'=>$_SESSION['uniacid'],'price'=>$postdata['endprice'],'createtime'=>time(),'status'=>1);
		$params=array('title'=>'收银台收款','tid'=> $tid,'fee'=>$postdata['endprice'],'auth_code'=>$postdata['auth_code']);
		$onewechat=pdo_getcolumn('jy_merch_user',array('uniacid' =>$_SESSION['uniacid'],'id'=>$merchid),'onewechat');
		$onewechat=json_decode($onewechat,true);
        if($onewechat && $onewechat['isopen'] && $onewechat['appid'] && $onewechat['wechat_mchid']){
			$config=array(
                 'appid'=>$onewechat['appid'],
                  'mch_id'=>$onewechat['wechat_mchid'],
                  'key'=>$onewechat['wechat_miyue'],
                  'apiclient_cert'=>$onewechat['cert_file']?ROOT_AT.$onewechat['cert_file']:'',
                  'apiclient_key'=>$onewechat['key_file']?ROOT_AT.$onewechat['key_file']:'',
            );	
			$res=cfc('wechat_pay',$config)->micro_pay($params);
		}else{
			$res=cfc('wechat_pay')->micro_pay($params);
		}
		if($res['result_code']=='SUCCESS' && $res['return_code']=='SUCCESS' && $res['total_fee']==$postdata['endprice']*100 && $tid== $res['out_trade_no']){
			$params=array(
				'id'=>$order_id,
				'title'=>'收银台收款',
				'fee'=>$postdata['endprice'],
				'pay_type'=>$postdata['paytype'],
				'back_url'=>'jy_merch/order.create1/payresult',
				'success_url'=>$success_url?:'jy_merch/manage.order_in/',
				'error_url'=>$error_url?:'jy_merch/manage.order_in/',
			);
			$payid=cfc('pay')->create_pay_order($params);
			pdo_update('core_paylog',array('transaction_id'=>$res['transaction_id'],'status'=>1,'paytime'=>$res['time_end']),array('uniacid'=>$_SESSION['uniacid'],'id'=>$payid));
			pdo_update('jy_weishop_order',array('pay_id'=>$payid,'status'=>1,'ispay'=>1,'paytype'=>'offsao','price'=>$postdata['endprice'],'deduction'=>$postdata['deduction'],'paytime'=>time()),array('uniacid'=>$_SESSION['uniacid'],'id'=>$order_id));
			if($order['price']==0){
                pdo_update('jy_weishop_order',array('pay_id'=>$payid,'status'=>1,'ispay'=>1,'paytype'=>'offsao','price'=>$postdata['endprice'],'deduction'=>$postdata['deduction'],'paytime'=>time()),array('uniacid'=>$_SESSION['uniacid'],'id'=>$order_id));
            }else{
                pdo_update('jy_weishop_order',array('pay_id'=>$payid,'status'=>1,'ispay'=>1,'paytype'=>'offsao','deduction'=>$postdata['deduction'],'paytime'=>time()),array('uniacid'=>$_SESSION['uniacid'],'id'=>$order_id));
            }
			//修改该订单下的所有商品为已支付状态
    		$order_goods = pdo_getall('jy_weishop_order_goods',array('uniacid'=>$_SESSION['uniacid'],'orderid'=>$order_id));
    		foreach($order_goods as $k=>$v){
    			pdo_update('jy_weishop_order_goods',array('ispay'=>1),array('uniacid'=>$_SESSION['uniacid'],'id'=>$v['id']));
    		}
			
			//需要用掉抵扣的优惠劵
    		if($order['couponid']){
    			model('jy_weishop/coupon')->usecoupon($order['couponid'],$order['ordersn']);
    		}
    		
    		if($order_id){
				model('jy_weishop/printmsg')->storeprint('',$order_id,1,1,'','','','',5,3);
			}
			
			
            //团长分销逻辑执行
            if($merchid){
    			$order['goods']=pdo_getall('jy_weishop_order_goods',array('orderid'=>$order_id,'merchid'=>$merchid));
    		}else{
    			$order['goods']=pdo_getall('jy_weishop_order_goods',array('orderid'=>$order_id));
    		}
    		/**
            ****线下收银业务逻辑团购,此处为团长分销机制
            **/
    	    model('jy_merch/retailcommission')->create($order);
    	    
    	    /**
    	    ***全员分销机制
    	    **/
    	    //model('jy_mteamfee/commission')->create($order);
            
			if($postdata['deduction']>0){
			    $zneworder = pdo_getcolumn('jy_weishop_order',array('uniacid'=>$_SESSION['uniacid'],'id'=>$order_id),'ordersn'); 
				$more = array('ordersn'=>$zneworder);
				if($postdata['merchid']){
				    
					model('jy_merch/member')->member_credit($postdata['merchid'],$postdata['mid'],'credit2',$postdata['deduction'],false,'jy_merch','消费储值抵扣',$tag='',$op_mid=0,$more);
					pdo_update('jy_weishop_order',array('deduction'=>$postdata['deduction']),array('uniacid'=>$_SESSION['uniacid'],'id'=>$order_id));
				}else{
					model('core/member')->member_credit($postdata['mid'],$postdata['mid'],'credit2',$postdata['deduction'],false,'jy_merch','消费储值抵扣',$tag='',$op_mid=0,$more);
					pdo_update('jy_weishop_order',array('deduction'=>$postdata['deduction']),array('uniacid'=>$_SESSION['uniacid'],'id'=>$order_id));
				}
			}
			
			$this->session('cashtype',1);
			//修改抹零记录的支付状态
		    pdo_update('jy_merch_mgoodslog',array('ispay'=>1),array('uniacid'=>$_SESSION['uniacid'],'ordersn'=>$order['ordersn'],'gtype'=>4,'merchid'=>$merchid));
			exi('收款成功','','jy_yiliao/worker.kaiyao//sendtype=2'); 
		}else{
			exi('收款失败','error');
		}		
	 }else if($postdata['paytype']==1){
	    $order=pdo_get('jy_weishop_order',array('uniacid'=>$_SESSION['uniacid'],'id'=>$order_id)); 
    	if($order['ispay'] ==1){
    		exi('该订单已经支付！','error','jy_yiliao/worker.kaiyao//sendtype=2');
    	}
        if($order['merchid'] && $this->plugin_exists('jy_merch')){
        	model('jy_merch/model')->up_pay($order);
        }
        //需要用掉抵扣的优惠劵
		if($order['couponid']){
			model('jy_weishop/coupon')->usecoupon($order['couponid'],$order['ordersn']);
		}
        //团长分销逻辑执行
        if($merchid){
			$order['goods']=pdo_getall('jy_weishop_order_goods',array('orderid'=>$order_id,'merchid'=>$merchid));
		}else{
			$order['goods']=pdo_getall('jy_weishop_order_goods',array('orderid'=>$order_id));
		}
		if($postdata['memberprice']){
		    $postdata['endprice'] = $postdata['memberprice'] - $order['level_de_price'] - $order['coupon_de_price'];
		}
        if($order['price']==0){
            pdo_update('jy_weishop_order',array('status'=>1,'price'=>$postdata['endprice'],'ispay'=>1,'deduction'=>$postdata['deduction'],'paytime'=>time(),'paytype'=>'offpay'),array('uniacid'=>$_SESSION['uniacid'],'id'=>$order_id));
        }else{
            pdo_update('jy_weishop_order',array('status'=>1,'ispay'=>1,'deduction'=>$postdata['deduction'],'price'=>$postdata['endprice'],'paytime'=>time(),'paytype'=>'offpay'),array('uniacid'=>$_SESSION['uniacid'],'id'=>$order_id));
        }
        /**
        ****线下收银业务逻辑团购,此处为团长分销机制
        **/
	    model('jy_merch/retailcommission')->create($order);

	    /**
	    ***全员分销机制
	    **/
	    //model('jy_mteamfee/commission')->create($order);

		//修改该订单下的所有商品为已支付状态
		$order_goods = pdo_getall('jy_weishop_order_goods',array('uniacid'=>$_SESSION['uniacid'],'orderid'=>$order_id));
		foreach($order_goods as $k=>$v){
			pdo_update('jy_weishop_order_goods',array('ispay'=>1),array('uniacid'=>$_SESSION['uniacid'],'id'=>$v['id']));
		}
		if($order_id){
			model('jy_weishop/printmsg')->storeprint('',$order_id,1,1,'','','','',5,3);
		}
		if($postdata['deduction']>0){
		    
		    $zneworder = pdo_getcolumn('jy_weishop_order',array('uniacid'=>$_SESSION['uniacid'],'id'=>$order_id),'ordersn'); 
			$more = array('ordersn'=>$zneworder);
			if($postdata['merchid']){
				model('jy_merch/member')->member_credit($postdata['merchid'],$postdata['mid'],'credit2',$postdata['deduction'],false,'jy_merch','消费储值抵扣',$tag='',$op_mid=0,$more);
				pdo_update('jy_weishop_order',array('deduction'=>$postdata['deduction']),array('uniacid'=>$_SESSION['uniacid'],'id'=>$order_id));
			}else{
				model('core/member')->member_credit($postdata['mid'],$postdata['mid'],'credit2',$postdata['deduction'],false,'jy_merch','消费储值抵扣',$tag='',$op_mid=0,$more);
				pdo_update('jy_weishop_order',array('deduction'=>$postdata['deduction']),array('uniacid'=>$_SESSION['uniacid'],'id'=>$order_id));
			}
		}
		//修改抹零记录的支付状态
		pdo_update('jy_merch_mgoodslog',array('ispay'=>1),array('uniacid'=>$_SESSION['uniacid'],'ordersn'=>$order['ordersn'],'gtype'=>4,'merchid'=>$merchid));
		$this->session('cashtype',1);
		exi('收款成功','','jy_yiliao/worker.kaiyao//sendtype=2');
	}else if($postdata['paytype']==2){
		pdo_update('jy_weishop_order',array('status'=>0),array('uniacid'=>$_SESSION['uniacid'],'id'=>$order_id));
		if($order_id){
			model('jy_weishop/printmsg')->storeprint('',$order_id,0,1,'','','','',1,1);
		}
		exi('下单成功','','jy_yiliao/worker.kaiyao//sendtype=2');
	}
}

if($_RQ['op']=='print4'){
	$postdata=get_postdata();
	$order_id=intval($postdata['oldorderid']);

	model('jy_weishop/printmsg')->storeprint('',$order_id,1,1,'','','','',4,3);

	exi('打印成功！');
}
if($_RQ['op']=='status3'){
	$postdata=get_postdata();
	$order_id=intval($postdata['oldorderid']);
	//清除session
	$this->session('cashtype','');
	//将该订单的赠品、退品、抹零明细数据全部变成已支付状态
	$param = array('uniacid'=>$_SESSION['uniacid'],'merchid'=>$merchid,'ordersn'=>$order_id,'ispay'=>0);
	$param['gtype'] = array(1,2,4);
	$slog = pdo_getall('jy_merch_mgoodslog',$param);
	foreach($slog as $val){
	   pdo_update('jy_merch_mgoodslog',array('ispay'=>1),array('id'=>$val['id']));
	}
	model('jy_weishop/order')->order_receive($order_id);
	exi('操作成功！');
}

if($_RQ['op']=='dazhe'){
	$postdata=get_postdata();
	
	$order_goods=pdo_get('jy_weishop_order_goods',array('uniacid'=>$_SESSION['uniacid'],'id'=>$postdata['id']),array('id','goodsid','orderid','optionid','total','total_price','price','optiondata'));
    //修改状态为打折
    pdo_update("jy_weishop_order_goods",array('isdiscount'=>$postdata['isdiscount']),array('uniacid'=>$_SESSION['uniacid'],'id'=>$postdata['id']));
	
	exi('操作成功！');
}
if($_RQ['op']=='tuicai'){
	$postdata=get_postdata();
	$order_goods=pdo_get('jy_weishop_order_goods',array('uniacid'=>$_SESSION['uniacid'],'id'=>$postdata['id']),array('id','goodsid','orderid','optionid','total','total_price','price','optiondata'));
	$order_goods2[] = $order_goods;
	//此处有退商品记录
	$order = pdo_get('jy_weishop_order',array('uniacid'=>$_SESSION['uniacid'],'id'=>$order_goods['orderid']));
	$tdata = array(
	  'uniacid'=>$_SESSION['uniacid'],
	  'num'=>$order_goods['total'],
	  'goodsid'=>$postdata['goodsid'],
	  'gimage'=>trim(json_decode($order_goods['goodsinfo'],true)['image']),
	  'gtitle'=>json_decode($postdata['goodsinfo'],true)['title'],
	  'gprice'=>$order_goods['total_price'],
	  'gtype'=>1,
	  'ordersn'=>$order_goods['orderid'],
	  'tableid'=>$order['tableid'],
	  'createtime'=>time(),
	  'merchid'=>$merchid
	);
	pdo_insert('jy_merch_mgoodslog',$tdata);
	//修改订单的价格
	pdo_update('jy_weishop_order',array('goodsprice -='=>$order_goods['total_price']),array('id'=>$order['id'],'uniacid'=>$_SESSION['uniacid']));
	
	//修改最终价格
	$neworder = pdo_get('jy_weishop_order',array('uniacid'=>$_SESSION['uniacid'],'id'=>$order['orderid']));
	pdo_update('jy_weishop_order',array('price -='=>$neworder['goodsprice']),array('id'=>$order['id'],'uniacid'=>$_SESSION['uniacid']));
	pdo_delete('jy_weishop_order_goods',array('uniacid'=>$_SESSION['uniacid'],'id'=>$postdata['id']));
	model('jy_weishop/printmsg')->storeprint('',$order_goods['orderid'],1,1,'','',$order_goods2,'',7,2);
	exi('操作成功！');
}
if($_RQ['op']=='tuicainum'){
	$postdata=get_postdata();
	$num=$postdata['tuinum']?:1;
	if($num>=$postdata['total']){
		exi('退商品数量不能大于等于当前数量！','error');
	}
	if(intval($num)<=0){
		exi('退商品数量不能小于等于0！','error');
	}
	$order_goods=pdo_get('jy_weishop_order_goods',array('uniacid'=>$_SESSION['uniacid'],'id'=>$postdata['id']),array('id','goodsid','orderid','optionid','total','total_price','price','optiondata','goodsinfo'));
	pdo_update('jy_weishop_order_goods',array('total -='=>$num,'total_price -='=>$order_goods['price']),array('uniacid'=>$_SESSION['uniacid'],'id'=>$postdata['id']));
	
		//此处有退商品记录
	$order = pdo_get('jy_weishop_order',array('uniacid'=>$_SESSION['uniacid'],'id'=>$order_goods['orderid']));
	$tdata = array(
	  'uniacid'=>$_SESSION['uniacid'],
	  'num'=>$num,
	  'goodsid'=>$order_goods['goodsid'],
	  'gtitle'=>json_decode($order_goods['goodsinfo'],true)['title'],
	  'gimage'=>trim(json_decode($order_goods['goodsinfo'],true)['image']),
	  'gprice'=>number_format($order_goods['price']*$num,2),
	  'gtype'=>1,
	  'ordersn'=>$order_goods['orderid'],
	  'tableid'=>$order['tableid'],
	  'createtime'=>time(),
	  'merchid'=>$merchid
	);
	pdo_insert('jy_merch_mgoodslog',$tdata);
	
	//修改订单的价格
	pdo_update('jy_weishop_order',array('goodsprice -='=>number_format($order_goods['price']*$num,2)),array('id'=>$order['id'],'uniacid'=>$_SESSION['uniacid']));
	
	//修改最终价格
	$neworder = pdo_get('jy_weishop_order',array('uniacid'=>$_SESSION['uniacid'],'id'=>$order['orderid']));
	pdo_update('jy_weishop_order',array('price -='=>$neworder['goodsprice']),array('id'=>$order['id'],'uniacid'=>$_SESSION['uniacid']));
	
	
	$order_goods['total']=$num;
	$order_goods2[] = $order_goods;
	model('jy_weishop/printmsg')->storeprint('',$order_goods['orderid'],1,1,'','',$order_goods2,'',7,2);
	exi('操作成功！');
}

//打折计算价格
if($_RQ['op']=='dzprice'){
	$postdata=get_postdata();
    if($postdata['ordersn']==''){
       exi('无参数请重新操作！','error','jy_yiliao/worker.kaiyao/');
    }
	//$order_goods=pdo_get('jy_weishop_order_goods',array('uniacid'=>$_SESSION['uniacid'],'id'=>$postdata['id']),array('id','goodsid','orderid','optionid','total','total_price','price','optiondata'));
    $order = pdo_get('jy_weishop_order',array('uniacid'=>$_SESSION['uniacid'],'ordersn'=>$postdata['ordersn']));
	$order_goodsprice = pdo_getsum('jy_weishop_order_goods',array('uniacid'=>$_SESSION['uniacid'],'orderid'=>$order['id'],'isdiscount'=>0),'total_price');
	
	$order_goodsprice1 = pdo_getsum('jy_weishop_order_goods',array('uniacid'=>$_SESSION['uniacid'],'orderid'=>$order['id'],'isdiscount'=>1),'total_price');
	//var_dump($order_goodsprice1);
	//die;
	//var_dump(round($order_goodsprice*($postdata['discount']/10)));
	//此处少一个优惠抵扣金额
	//566
	
	$dzprice = round($order_goodsprice*($postdata['discount']/10) + $order_goodsprice1,2);

	pdo_update("jy_weishop_order",array("merchisdzprice"=>$dzprice,'mcdiscount'=>$postdata['discount']),array('uniacid'=>$_SESSION['uniacid'],'id'=>$order['id']));
	exi($dzprice);
}

//抹零计算价格
if($_RQ['op']=='gaiprice'){
	$postdata=get_postdata();
    //此处没有订单号
    if($postdata['ordersn']==''){
       exi('无参数请重新操作！','error','jy_yiliao/worker.kaiyao/');
    }
    $order = pdo_get('jy_weishop_order',array('uniacid'=>$_SESSION['uniacid'],'ordersn'=>$postdata['ordersn']));
    
    //此处有抹零记录
    $tdata = array(
	  'uniacid'=>$_SESSION['uniacid'],
	  'gprice'=>number_format(($order['goodsprice']-$postdata['newendprice']),2),
	  'gtype'=>4,
	  'gtitle'=>'整单抹零',
	  'gimage'=>'../core/resource/images/molin.png',
	  'ordersn'=>$postdata['ordersn'],
	  'tableid'=>$order['tableid'],
	  'createtime'=>time(),
	  'merchid'=>$merchid
	);

	//查询是否给该订单抹零
	$mlog = pdo_get('jy_merch_mgoodslog',array('uniacid'=>$_SESSION['uniacid'],'ordersn'=>$order['id']));
	if(!$mlog){
	    pdo_insert('jy_merch_mgoodslog',$tdata);
	}else{
	    pdo_update('jy_merch_mgoodslog',$tdata,array('uniacid'=>$_SESSION['uniacid'],'ordersn'=>$order['id']));
	}
	pdo_update('jy_weishop_order',array('molin_price'=>number_format(($order['goodsprice']-$postdata['newendprice']),2)),array('uniacid'=>$_SESSION['uniacid'],'id'=>$order['id'],'merchid'=>$merchid));
	exi($postdata['newendprice']);
}

if($_RQ['op']=='xzywy'){
	$postdata=get_postdata();

	pdo_update('jy_weishop_order',array('storeworkerid'=>$postdata['storeworkerid']),array('uniacid'=>$_SESSION['uniacid'],'ordersn'=>$postdata['ordersn']));
	//$worker = pdo_get();
	//exi($w_mid);
	exi('操作成功！');
}

if($_RQ['op']=='songcai'){
	$postdata=get_postdata();

	pdo_update('jy_weishop_order_goods',array('price'=>0,'total_price'=>0,'buytype'=>2),array('uniacid'=>$_SESSION['uniacid'],'id'=>$postdata['id']));
	//此处有赠送商品记录
	$order = pdo_get('jy_weishop_order',array('uniacid'=>$_SESSION['uniacid'],'id'=>$postdata['orderid']));
	$tdata = array(
	  'uniacid'=>$_SESSION['uniacid'],
	  'num'=>$postdata['total'],
	  'goodsid'=>$postdata['goodsid'],
	  'gtitle'=>json_decode($postdata['goodsinfo'],true)['title'],
	  'gimage'=>trim(json_decode($postdata['goodsinfo'],true)['image']),
	  'gprice'=>number_format($postdata['price']*$postdata['total'],2),
	  'gtype'=>2,
	  'ordersn'=>$postdata['orderid'],
	  'tableid'=>$order['tableid'],
	  'createtime'=>time(),
	  'merchid'=>$merchid
	);
	pdo_insert('jy_merch_mgoodslog',$tdata);
	exi('操作成功！');
}